#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
依赖注入示例
演示了 FastAPI 的依赖注入系统
"""

from fastapi import FastAPI, Depends, Header, Query, HTTPException

app = FastAPI()

# 简单依赖
async def get_common_parameters(q: Union[str, None] = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

# 使用依赖
@app.get("/items/")
async def read_items(commons: dict = Depends(get_common_parameters)):
    return commons

# 带 yield 的依赖
class DBSession:
    def __init__(self):
        self.data = "Database Connection"
    
    def close(self):
        print("Database connection closed")

async def get_db():
    db = DBSession()
    try:
        yield db
    finally:
        db.close()

@app.get("/database/")
async def read_database(db: DBSession = Depends(get_db)):
    return {"db": db.data}

# 子依赖
async def verify_token(x_token: str = Header(...)):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")
    return x_token

async def verify_key(x_key: str = Query(...)):
    if x_key != "fake-secret-key":
        raise HTTPException(status_code=400, detail="X-Key query invalid")
    return x_key

@app.get("/items-with-dependencies/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items_with_dependencies():
    return [{"item": "Foo"}, {"item": "Bar"}]

# 类作为依赖
class CommonQueryParams:
    def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
        self.q = q
        self.skip = skip
        self.limit = limit

@app.get("/items-with-class/")
async def read_items_with_class(commons: CommonQueryParams = Depends()):
    return commons.__dict__

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8005, log_level="info")